package com.leyou.auth.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.auth.config.OSSProperties;
import com.leyou.auth.dto.AliOssSignatureDTO;
import com.leyou.auth.service.AliAuthService;
import com.leyou.common.exceptions.LyException;
import org.springframework.stereotype.Service;

import java.sql.Date;

/**
 * @author 虎哥
 */
@Service
public class AliAuthServiceImpl implements AliAuthService {

    private final OSSProperties prop;
    private final OSS client;

    public AliAuthServiceImpl(OSSProperties prop, OSS client) {
        this.prop = prop;
        this.client = client;
    }

    @Override
    public AliOssSignatureDTO generateOssSignature() {
        try {
            // 过期时间
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // 上传文件的策略条件
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            // 对文件上传的策略条件 做编码，形成字符串
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 生成签名
            String postSignature = client.calculatePostSignature(postPolicy);

            return AliOssSignatureDTO.of(
                    prop.getAccessKeyId(),
                    prop.getHost(),
                    encodedPolicy,
                    postSignature,
                    expireEndTime / 1000,
                    prop.getDir());

        } catch (Exception e) {
            throw new LyException(500, e);
        }
    }
}
